package com.bwie.auth.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.bwie.auth.exception.LoginException;
import com.bwie.auth.remote.UserRemote;
import com.bwie.auth.service.AuthUserService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserRequest;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: AuthUserServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 张雨乐
 * @date: 2025/10/22 9:41
 */
@Service
public class AuthUserServiceImpl implements AuthUserService {
    @Autowired
    UserRemote userRemote;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Result nameLogin(UserRequest userRequest) {
        String name = userRequest.getName();
        String pwd = userRequest.getPwd();

        if (StrUtil.isBlank(name)){
            throw new LoginException(1001,"账号为空");
        }
        if (StrUtil.isBlank(pwd)){
            throw new LoginException(1001,"密码为空");
        }
        if (redisTemplate.hasKey(JwtConstants.DETAILS_USER_ID+name)){
            throw new LoginException(1002,"失败次数大于3次稍后重试");
        }
        //因为我们用名字查询可能会有多个名字一样的值，所以用list来接收
        Result<User> list=userRemote.nameLogin(userRequest);
        User user = list.getData();
        if (user==null){
            //没有找到用户
            userRemote.userAdd(userRequest);
        }
        //找到用户了
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(pwd,user.getPwd())){
            if (redisTemplate.hasKey(name)){
                Integer o = (Integer) redisTemplate.opsForValue().get(name);
                if (o>=3){
                    //失败次数大于3次让五分钟后重试
                    redisTemplate.opsForValue().set(JwtConstants.DETAILS_USER_ID+name,5,5,TimeUnit.MINUTES);
                    throw new LoginException(1003,"失败次数大于3次让五分钟后重试");
                }else {
                    //失败次数大于3次让五分钟后重试
                    redisTemplate.opsForValue().set(name,o++,2,TimeUnit.MINUTES);
                    throw new LoginException(1003,"已失败"+(o+1)+"次");
                }
            }else {
                //第一次登录失败2分钟后失效
                redisTemplate.opsForValue().set(name,1,2,TimeUnit.MINUTES);
            }
        }
        Map<String, Object> map = new HashMap<>();
        String userKey = IdUtil.fastSimpleUUID();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey,user,30,TimeUnit.MINUTES);
        UserResponse userResponse = new UserResponse();
        userResponse.setTime("30TIME");
        userResponse.setToken(token);
        return Result.success(userResponse);
    }

    /**
     * 普通图片验证码
     * @return
     */
    @Override
    public Result code() {
        String s = RandomUtil.randomNumbers(4);
        //应该吧JwtConstants.DETAILS_USER_ID换成本机地址来存取
        redisTemplate.opsForValue().set(JwtConstants.DETAILS_USER_ID,s,2, TimeUnit.MINUTES);
        return Result.success(s);
    }

    /**
     * 发送手机号验证码的
     * @param userRequest
     * @return
     */
    @Override
    public Result phoenCode(UserRequest userRequest) {
        String code = userRequest.getCode();
        if (StrUtil.isBlank(code)){
            throw new LoginException(1001,"验证码为空");
        }
        String codeTo = (String) redisTemplate.opsForValue().get(JwtConstants.DETAILS_USER_ID);
        if (!codeTo.equals(code)){
            throw new LoginException(1001,"验证码错误");
        }
        //查询手机号唯一性
        Result<User>result=userRemote.phoneLogin(userRequest);
        User user = result.getData();
        if (user==null){
            //没有找到用户去添加用户
            userRemote.userAdd(userRequest);
        }
        String s = RandomUtil.randomNumbers(4);
        //应该吧验证码换成本机地址来存取
        redisTemplate.opsForValue().set(userRequest.getPhone(),s,2, TimeUnit.MINUTES);
        return Result.success(s);
    }

    /**
     * 手机号登录
     * @param userRequest
     * @return
     */

    @Override
    public Result phoneLogin(UserRequest userRequest) {
        String phone = userRequest.getPhone();
        String phoneCode = userRequest.getPhoneCode();
        if (StrUtil.isBlank(phone)){
            throw new LoginException(1001,"手机号为空");
        }
        if (StrUtil.isBlank(phoneCode)){
            throw new LoginException(1001,"验证码为空");
        }
        if (!redisTemplate.hasKey(userRequest.getPhone())){
            throw new LoginException(1001,"验证码未发送");
        }
        String phoneCodeTo = (String) redisTemplate.opsForValue().get(phone);
        if (!phoneCode.equals(phoneCodeTo)){
            throw new LoginException(1001,"验证码错误");
        }
        //查询手机号唯一性
        Result<User>result=userRemote.phoneLogin(userRequest);
        User user = result.getData();
        if (user==null){
            //没有找到用户
            userRemote.userAdd(userRequest);
        }
        Map<String, Object> map = new HashMap<>();
        String userKey = IdUtil.fastSimpleUUID();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey,user,30,TimeUnit.MINUTES);
        UserResponse userResponse = new UserResponse();
        userResponse.setTime("30TIME");
        userResponse.setToken(token);
        return Result.success(userResponse);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode("12345");
        System.out.println(encode);
    }


}
